<?php
namespace app\common\logic\ad\driver;


use app\common\logic\ad\Driver;
use app\common\model\ad\Ads;
use app\common\model\cast\Item;
use fast\Form;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * Created by PhpStorm.
 * User: yangchunfu
 * Date: 2019/12/24
 * Time: 4:36 PM
 */

class Cast extends Driver
{
    protected $options = [
    ];
    //1代表单频道 2代表多频道
    protected $rule = [1, 2];

    protected $htmlTpl = 'cast.html';
    protected $ruleWhere = [
        'mark' => 'cast'
    ];



    public function __construct($options)
    {
        parent::__construct($options);
        if (!$this->options['rule']) {
            throw new ValidateException('rule必须传递');
        }
    }

    /**
     * 重组频道
     */
    public function getCastItem() {
        $item = new Item();
        $items = $item->where('type', 0)->column('id, name');

        return $items;
    }

    /**
     * 修改
     * @param array $data 要添加的数据
     * @return boolean
     */
    public function select($where = []){

    }


    /**
     * 获取规则html
     * @param int $ads_id
     * @return string
     */
    public function insertRule($ads_id = null)
    {
        if (self::$curRule == 2) {
            return '';
        }

        $cast_item_id = null;
        if ($ads_id) {
            //如果传递了广告id，那么可以获取
            $cast_item_id = $this->ruleModel->where($this->getRule())->where(['ad_ads_id' => $ads_id])->value('cast_item_id');
        }

        $items = $this->getCastItem();
        $items = array_merge(['0' => '--请选择广告所属栏目--'], $items);
        $select_string = build_select('rules[cast_item_id]', $items, $cast_item_id,[
            'class'=>'form-control',
            'data-rule'=>'required'
        ]);
        $html = <<<EOD
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">请选择栏目:</label>
        <div class="col-xs-12 col-sm-8">
            {$select_string}               
        </div>
    </div>
EOD;

        return $html;
    }



    /**
     * 修改广告
     * @param array $data 要添加的数据
     * @param object $row 要添加的数据
     * @return mixed
     */
    public function edit(Ads $row, $data = []) {
        $rule_where = $this->getRule();
        $rule_where['ad_ads_id'] = $row->id;
        Db::startTrans();
        try {
            if (self::$curRule != 2) {
                $this->ruleModel->where($rule_where)->setField('cast_item_id', $this->options['cast_item_id']);
            }
            $row->allowField(true)->save($data);
            Db::commit();
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

}